<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use EasyWeChat\Foundation\Application;
use EasyWeChat\Message\Image;
class Wechat extends Base_Controller {


    private $_token = 'jianlou123';
    private $avatar_path;
    private $_logFile = '/www/wwwroot/wb.yshfengmi.com/uploads/easywechat.log';
	function __construct ()
	{
		parent::__construct();
        $this->avatar_path = FCPATH.'uploads/avatar/';
    }

    /**
     * 接受消息通知
     */
	public function service(){
        // 处理消息
        $options = [
            'debug'  => false,
            'app_id' => config_item("app_id"),
            'secret' => config_item("app_secret"),
            'token'  => $this->_token,
            'log' => [
                'level' => 'debug',
                'file'  => $this->_logFile, // XXX: 绝对路径！！！！
            ],
        ];
        $app = new Application($options);
        $server = $app->server;
        $user = $app->user;
        $server->setMessageHandler(function ($message) use ($user){
            $text = '空空';
            if ($message->MsgType) {
                $text = $this->{$message->MsgType}($message, $user);
            }
            return $text;
        });
        $response = $server->serve();
        // 将响应输出
        $response->send();
	}

    /**
     * 绑定上下级
     * @param $openid
     * @param $referee_id
     */
    public function subcribe_bind($openid,$referee_id){
        $options = [
            'debug'  => false,
            'app_id' => config_item("app_id"),
            'secret' => config_item("app_secret"),
            'token'  => $this->_token,
            'log' => [
                'level' => 'debug',
                'file'  => $this->_logFile, // XXX: 绝对路径！！！！
            ],
        ];
        $app = new Application($options);
        $user = $app->user;
        $userService = $user->get($openid);
        $userArr = $userService->toArray();
        // 微信用户信息入库
        $this->wxUser_m->refereer_subscribe($userArr);
        // 查看用户是否已注册
        $wxuser = $this->wxUser_m->get_weixin_users_by_openid($openid);
        if(empty($wxuser['user_id'])){
            // 新用户数据入库
            $salt =get_salt();
            $admin = array(
                'user_name' => $userService->nickname,
                'user_uname' => $userService->nickname,
                'user_password' =>  password_dohash("123456",$salt),
                'user_salt' => $salt,
                'user_credit' => $this->config->item('credit_start'),
                'user_money'=> 0,
                'user_group'=> 4,
                'user_regtime' => time(),
                'user_logtime' => time(),
                'user_lock'=>0,
                'user_avatar'=>$userService->headimgurl,
            );
            $this->user_m->register($admin);
            $new_id = $this->db->insert_id();
            $update_arr = array(
                'user_key'=>password_dohash($new_id,$salt),
                'agent_id'=>$referee_id
            );
            $this->user_m->update_user($new_id,$update_arr);
            $this->groupAcess_m->insert_user_access(['uid'=>$new_id,'group_id'=>4]);
            // 回写user_id
            $this->wxUser_m->update_weixin_users_by_openid($openid,["user_id"=>$new_id]);
        }else{
            $update_user = $this->user_m->get_user_by_user_id($wxuser['user_id']);
            if(empty($update_user['agent_id'])){
                $update_arr = array(
                    'agent_id'=>$referee_id
                );
                $this->user_m->update_user($wxuser['user_id'],$update_arr);
            }
        }
    }


    /**
     * 创建菜单
     */
    public function createMenu() {
        $options = [
            'debug'  => false,
            'app_id' => config_item("app_id"),
            'secret' => config_item("app_secret"),
            'log' => [
                'level' => 'debug',
                'file'  => $this->_logFile, // XXX: 绝对路径！！！！
            ],
        ];
        $app = new Application($options);
        $domain = "http://wx.91shunshi.com";
        $buttons = [
            [
                "name"       => "我要办理",
                "sub_button" => [
                    [
                        "type" => "view",
                        "name" => "宽带新装",
                        "url"  => $domain."/index.php/wx/home/wb_install"
                    ],
                    [
                        "type" => "view",
                        "name" => "宽带报修",
                        "url"  => $domain."/index.php/wx/home/wb_repair",
                    ],
                    [
                        "type" => "view",
                        "name" => "宽带迁移",
                        "url"  => $domain."/index.php/wx/home/wb_move",
                    ],
                ]
            ],
            [
                "name" => "套餐资费",
                "sub_button" => [
                    [
                        "type" => "view",
                        "name" => "58元套餐",
                        "url"  => "https://www.10086.cn/kdzq/index/gd/",
                    ],
                    [
                        "type" => "view",
                        "name" => "38元套餐",
                        "url"  => "https://www.10086.cn/kdzq/index/gd/",
                    ],
                    [
                        "type" => "view",
                        "name" => "128元套餐",
                        "url"  => "https://www.10086.cn/kdzq/index/gd/",
                    ],
                ]
            ],
            [
                "type" => "view",
                "name" => "我的业务",
                "url" => $domain."/index.php/wx/home/my_wb"
            ]
        ];
        $res = $app->menu->add($buttons);
        pp($res);
    }

    /**
     * 上传素材
     */
    public function material(){
        $options = [
            'debug'  => false,
            'app_id' => config_item("app_id"),
            'secret' => config_item("app_secret"),
            'log' => [
                'level' => 'debug',
                'file'  => $this->_logFile, // XXX: 绝对路径！！！！
            ],
        ];
        $app = new Application($options);
        // 永久素材
        $material = $app->material;
        $result = $material->uploadImage(FCPATH.'public/wap/images/about.jpg');
        $mediaId = $result->media_id;
        $this->load->model('wxMedia_m');
        $data = array(
            'media_id'=>$mediaId,
            'url'=>$result->url,
            'title'=>"了解捡漏",
            'create_time'=>time(),
            'modify_time'=>time()
        );
        $this->wxMedia_m->add_weixin_media($data);
        pp($result);exit();
    }

    // 处理微信、消息 开始
    private function event($message, $user) {
        // 事件消息
        if ($message->Event == 'subscribe') {
            // 未关注者通过带参二维码关注公众号
            if(isset($message->EventKey)){
                $param = explode("_",$message->EventKey);
                $referee_id = $param[1];
                $openid = $message->FromUserName;
                $this->subcribe_bind($openid,$referee_id);
            }else{
                $openid = $message->FromUserName;
                $this->subcribe_bind($openid,0);
            }
        } elseif ($message->Event == 'SCAN') {
            // 已关注者扫描带参二维码进入公众号
            if(isset($message->EventKey)){
                $referee_id = $message->EventKey;
                $openid = $message->FromUserName;
                file_put_contents($this->_logFile, json_encode([$message->EventKey,$referee_id,$openid]), FILE_APPEND);
                $this->subcribe_bind($openid,$referee_id);
            }
        }
        $text = $this->config->item('wx_reply');
        return $text;
    }
    private function text($message, $user) {
        if ($message->Content == '了解捡漏') {
            $text = new Image();
            $text->media_id = 'MCvLZ83nk-7LkWFuVgmkA0dRPAxdcILrQ0RSE3A-eWw';
            return $text;
        }
        return $text = $this->config->item('wx_reply');
    }
    private function image($message, $user) {
        return $text = $this->config->item('wx_reply');
    }
    private function voice($message, $user) {
        return $text = $this->config->item('wx_reply');
    }
    private function video($message, $user) {
        return $text = $this->config->item('wx_reply');
    }
    private function location($message, $user) {
        return $text = $this->config->item('wx_reply');
    }
    private function link($message, $user) {
        return $text = $this->config->item('wx_reply');
    }
    // 处理微信、消息 结束

    public function clean_cs() {
        $this->load->helper('cookie');
        $this->session->unset_userdata("wechat_user");
        $this->session->unset_userdata("target_url");
        $this->session->unset_userdata("wechat_user_info");
        $uid=$this->session->userdata('user_id');
        $this->user_m->del_user_key_by_user_id($uid);
        $this->session->unset_userdata('user_id');
        setcookie('loveme', '', time() - 3600, '/', '', false, true);

        delete_cookie("machine_key");
        delete_cookie("qq_city");
        delete_cookie("qq_lat");
        delete_cookie("qq_lng");
        delete_cookie("user_referee");
        foreach ($_COOKIE as $key => $value) {
            setcookie($key, null);
        }
        pp("清楚缓存成功");exit();
    }
    public  function session(){
        pp($_SESSION);
    }
}
